import { createRouter, createWebHashHistory } from 'vue-router'
import cart from '@/views/layout/cart/cart.vue'
import store from '@/store'
import SearchList from '@/views/search/SearchList.vue'

const routes = [
  { path: '/login', component: () => import('@/views/login') },
  {
    path: '/',
    component: () => import('@/views/layout/index.vue'),
    redirect: '/home',
    children: [
      {
        path: '/home',
        component: () => import('@/views/layout/home/home.vue')
      },
      {
        path: '/category',
        component: () => import('@/views/layout/category/category.vue')
      },
      {
        path: '/cart',
        component: cart
      },
      {
        path: '/user',
        component: () => import('@/views/layout/user/user.vue')
      }
    ]
  },
  { path: '/myorder', component: () => import('@/views/myorder') },
  { path: '/pay', component: () => import('@/views/pay') },
  { path: '/prodetail/:id', component: () => import('@/views/prodetail') },
  { path: '/search', component: () => import('@/views/search/index.vue') },
  {
    path: '/searchlist',
    name: SearchList,
    component: () => import('@/views/search/SearchList.vue')
  },
  { path: '/error', component: () => import('@/views/error/404') }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// GOOD
// 导航拦截
// 定义一个数组，专门存放用户所有需要权限访问的页面
const authUrls = ['/pay', '/myorder']

router.beforeEach((to, from, next) => {
  if (!authUrls.includes(to.path)) {
    // 非权限页面直接放行
    next()
    return
  }
  const token = store.getters.token
  if (token) {
    next()
  } else {
    next('/login')
  }
})

export default router
